<template>
  <el-form label-width="100px" width="80%" style="width: 800px">
    <el-form-item label="Spu名称" style="width: 500px">
      <el-input
        placeholder="输入spu名称"
        v-model="paramsData.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="Spu品牌" style="width: 500px">
      <el-select
        placeholder="请选择spu品牌"
        style="width: 500px"
        v-model="paramsData.tmId"
      >
        <el-option
          v-for="item in allTrademark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="Spu描述" style="width: 500px">
      <el-input
        v-model="paramsData.description"
        type="textarea"
        placeholder="输入spu描述"
      ></el-input>
    </el-form-item>
    <!-- 照片墙 -->
    <el-form-item label="SPU图标">
      <el-upload
        v-model:file-list="allImage"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :before-upload="beforeAvatarUpload"
        :on-remove="handleRemove"
      >
        <el-icon><Aim /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          alt="Preview Image"
          :src="dialogImageUrl"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <!-- Spu销售属性 -->
    <el-form-item label="Spu销售属性">
      <el-select
        v-model="selectAttrValue"
        :placeholder="
          unSelectSaleAttr.length
            ? `还可选择${unSelectSaleAttr.length}条属性`
            : '已选择全部属性'
        "
      >
        <el-option
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
          :value="item.name + ':' + item.id"
        />
      </el-select>
      <el-button
        :disabled="!selectAttrValue"
        @click="addSpuAttr"
        type="primary"
        size="default"
        icon="Plus"
        style="margin: 0 10px"
      >
        添加属性
      </el-button>
    </el-form-item>
    <!-- 表格 -->
    <el-form-item>
      <el-table border :data="hasSpuAttr">
        <el-table-column
          label="序号"
          align="center"
          width="100px"
          type="index"
        ></el-table-column>
        <el-table-column
          label="销售属性名称"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <template #default="{ row, $index }">
            <el-tag
              style="margin: 5px"
              v-for="(tag, ind) in row.spuSaleAttrValueList"
              :key="tag.id"
              class="mx-1"
              closable
              @close="row.spuSaleAttrValueList.splice(ind, 1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              :ref="(vc:any) => inputArr[$index] = vc"
              v-model="row.addAttrValue"
              v-if="row.flag"
              size="small"
              placeholder="输入属性值"
              style="width: 100px"
              @blur="toLook(row)"
            ></el-input>
            <el-button
              v-else
              type="primary"
              size="small"
              icon="Plus"
              @click="toEdit(row, $index)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button
              @click="hasSpuAttr.splice($index, 1)"
              type="danger"
              size="small"
              icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button @click="saveSpu" type="primary" size="small">保存</el-button>
      <el-button size="small" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, nextTick, ref } from 'vue'
// 引入接口
import {
  reqAllTradeMark,
  reqAllImage,
  reqSaleAttrHasList,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from '@/api/product/spu'
import type {
  spuData,
  tradeMarkResponseData,
  trademarkResponse,
  imageResponseData,
  AllImageResponse,
  spuAttrResponseData,
  SpuSaleAttrResponse,
  allAttrData,
  allAttrResponse,
  spuSaleAttrValue,
} from '@/api/product/spu/type'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
const $emit = defineEmits(['changeShowType'])
const cancel = () => {
  $emit('changeShowType', {
    flag: 0,
    params: 'update',
  })
}
const inputArr = ref<any>([])
// 切换展示
const toLook = (row: spuAttrResponseData) => {
  row.flag = false
  // 空值判断
  if (!row.addAttrValue?.trim()) return (row.addAttrValue = '')
  const { addAttrValue, baseSaleAttrId } = row
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === addAttrValue
  })
  if (repeat) {
    row.addAttrValue = ''
    ElMessage.error('已输入该属性值')
    return
  }
  let newSaleAttrValue: spuSaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: addAttrValue as string,
  }
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.addAttrValue = ''
}
// 切换增加属性值
const toEdit = (row: spuAttrResponseData, index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[index].focus()
  })
}
// 点击添加属性
const addSpuAttr = () => {
  const newArr = selectAttrValue.value.split(':')
  const [saleAttrName, baseSaleAttrId] = newArr
  const data = {
    saleAttrName,
    baseSaleAttrId,
    spuSaleAttrValueList: [],
  }
  hasSpuAttr.value.push(data)
  selectAttrValue.value = ''
}
// 定义未选择销售属性
const unSelectSaleAttr = computed(() => {
  let unSelect = allSpuAttr.value.filter((item) => {
    return hasSpuAttr.value.every((res) => item.name !== res.saleAttrName)
  })
  return unSelect
})
const selectAttrValue = ref('')

// 预览image变量
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
// 点击image预览效果
const handlePictureCardPreview = (uploadFile: any) => {
  dialogVisible.value = true
  dialogImageUrl.value = uploadFile.url
}
// 上唇图片完成之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 > 4) {
      ElMessage.error('请上传低于4M的图片')
      return false
    }
    return true
  } else {
    ElMessage.error('请上传以png,jpeg,gif类型图片')
  }
}
// 删除图片
const handleRemove = () => {
  ElMessage.info('移除成功')
}
// 收集trademark
const allTrademark = ref<tradeMarkResponseData[]>([])
// 收集image
const allImage = ref<imageResponseData[]>([])
// 收集已有spu属性
const hasSpuAttr = ref<spuAttrResponseData[]>([])
// 获取所有spu属性
const allSpuAttr = ref<allAttrData[]>([])
const paramsData = ref<spuData>({
  category3Id: '',
  spuName: '',
  tmId: '',
  description: '',
  spuImageList: [],
  spuSaleAttrList: [],
})
// 点击保存
const saveSpu = async () => {
  paramsData.value.spuImageList = allImage.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  paramsData.value.spuSaleAttrList = hasSpuAttr.value
  const res = await reqAddOrUpdateSpu(paramsData.value)
  $emit('changeShowType', {
    flag: 0,
    params: paramsData.value.id ? 'update' : 'add',
  })
  if (res.code === 200) {
    ElMessage.success(paramsData.value.id ? '更新成功' : '添加成功')
  } else {
    ElMessage.error('操作失误,请重试')
  }
}
// 初始化spu展示
const initUpdateSpu = async (spu: spuData) => {
  initAddSpu(0)
  paramsData.value = spu
  // 获取所有image
  const resAllImage: AllImageResponse = await reqAllImage(spu.id as number)
  allImage.value = resAllImage.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  // 已有spu的属性列表
  const resHasSpu: SpuSaleAttrResponse = await reqSaleAttrHasList(
    spu.id as number,
  )
  hasSpuAttr.value = resHasSpu.data
}
const initAddSpu = async (c3Id: number | string) => {
  allImage.value = []
  hasSpuAttr.value = []
  // 获取所有trademark
  const resAllTrademark: trademarkResponse = await reqAllTradeMark()
  allTrademark.value = resAllTrademark.data
  // 所有spu属性
  const resAllSpuAttr: allAttrResponse = await reqAllSaleAttr()
  allSpuAttr.value = resAllSpuAttr.data
  if (!c3Id) return
  // 清空数据
  Object.assign(paramsData.value, {
    category3Id: '',
    spuName: '',
    tmId: '',
    id: '',
    description: '',
    spuImageList: [],
    spuSaleAttrList: [],
  })
  // 清空image和已选择spu属性
  allImage.value = []
  hasSpuAttr.value = []
  selectAttrValue.value = ''
  paramsData.value.category3Id = c3Id
}
defineExpose({
  initUpdateSpu,
  initAddSpu,
})
</script>

<script lang="ts">
export default {
  name: 'Spu',
}
</script>

<style lang="scss" scoped></style>
